//
//  headimagedb.m
//  tcpoctest
//
//  Created by apple on 13-3-11.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "headimagedb.h"

@implementation headimagedb

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    [db executeUpdate:@"create table if not exists headimage(mail text primary key,imageurl text)"];
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertHeadImageUrl:(NSString *)mail withURL:(NSString *)url
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT imageurl FROM headimage WHERE mail = '%@'",mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    FMResultSet *s = [db executeQuery:strsql];
    if([s next])
    {
        strsql = [NSString stringWithFormat:@"update headimage set imageurl = '%@' WHERE mail = '%@'",
                  url,
                  mail];
    }
    else
    {
        strsql = [NSString stringWithFormat:@"insert into headimage(mail,imageurl) values('%@','%@')",
                  mail,
                  url];
    }
    
    [db executeUpdate:strsql];
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)deleteHImageByMail:(NSString *)mail
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:@"DELETE FROM headimage WHERE mail='%@'"
                        ,mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    [db executeUpdate:strsql];
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM headimage"];
    FMResultSet *s = [db executeQuery:strsql];
    
    [[DataControl shareControl].HeadImageDic removeAllObjects];
    
    while ([s next])
    {
        [[DataControl shareControl].HeadImageDic setObject:[s stringForColumn:@"imageurl"]
                                                    forKey:[s stringForColumn:@"mail"]];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
